from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_, or_
db = SQLAlchemy()
class MyModel(db.Model):
field1 = db.Column(db.Integer)
field2 = db.Column(db.String)
# 其他字段...
def build_comparison(model, field, operator, value):
# 映射字符串运算符到 SQLAlchemy 方法
operators = {
'==': lambda f: f == value,
'>': lambda f: f > value,
'<': lambda f: f < value,
'>=': lambda f: f >= value,
'<=': lambda f: f <= value,
'!=': lambda f: f != value,
# 可以根据需要添加更多运算符
}
# 获取模型的字段属性
field_attr = getattr(model, field)
# 使用映射的运算符来构建比较表达式
if operator in operators:
comparison = operators[operator](field_attr)
return comparison
else:
raise ValueError(f"Unsupported operator: {operator}")
def build_query(model, conditions):
query = model.query
# 如果提供了 conditions,则使用 or_ 连接它们
if conditions:
filters = []
for field, operator, value in conditions:
comparison = build_comparison(model, field, operator, value)
filters.append(comparison)
# 使用 or_ 将所有比较表达式连接起来
query = query.filter(or_(*filters))
return query
# 示例条件
conditions = [['field1', '>', 10], ['field2', '<=', 'valueB']]
# 构建查询
query = build_query(MyModel, conditions)
# 执行查询并获取结果
results = query.all()
for result in results:
print(result)